/**
 * Witontek.com.
 * Copyright (c) 2012-2016 All Rights Reserved.
 */
package test.jaxb;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @author CST
 * @version $Id: XmlUtil.java, v 0.1 2018年2月1日 上午8:38:01 CST Exp $
 */
public class XmlUtil {
    /**
    * Logger for this class
    */
    private static final Logger logger = LoggerFactory.getLogger(XmlUtil.class);

    public static <T> T convertToObj(Class<T> clazz, String xml) {
        try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            return clazz.cast(unmarshaller.unmarshal(new StringReader(xml)));
        } catch (Exception e) {
            logger.error("", e);
            return null;
        }
    }

    public static String convertToXml(Object obj) {
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            StringWriter sw = new StringWriter();
            marshaller.marshal(obj, sw);
            return sw.toString();
        } catch (Exception e) {
            logger.error("", e);
            return null;
        }
    }

}
